import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/composables/useApi'
import Cookies from 'js-cookie'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(Cookies.get('token') || '')
  const user = ref(null)
  
  const isAuthenticated = ref(!!token.value)
  
  // 登录
  const login = async (username, password) => {
    try {
      const response = await api.post('/auth/login', { username, password })
      token.value = response.data.token
      Cookies.set('token', token.value)
      isAuthenticated.value = true
      return response
    } catch (error) {
      throw error
    }
  }
  
  // 注册
  const register = async (userData) => {
    try {
      const response = await api.post('/auth/register', userData)
      token.value = response.data.token
      Cookies.set('token', token.value)
      isAuthenticated.value = true
      return response
    } catch (error) {
      throw error
    }
  }
  
  // 退出登录
  const logout = () => {
    token.value = ''
    Cookies.remove('token')
    user.value = null
    isAuthenticated.value = false
  }
  
  return {
    token,
    user,
    isAuthenticated,
    login,
    register,
    logout
  }
})

